<template>
  <!-- 移动设备上使用可见的权限请求界面 -->
  <div v-if="showPermissionPrompt" class="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
    <div class="bg-white rounded-xl p-6 max-w-md w-full shadow-2xl">
      <div class="text-center">
        <div class="flex justify-center mb-4">
          <div class="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center">
            <i class="fa fa-camera text-primary text-2xl"></i>
          </div>
        </div>
        <h3 class="text-lg font-bold text-neutral mb-2">摄像头访问权限</h3>
        <p class="text-gray-600 mb-6">
          {{ errorMessage || '请授予摄像头权限以使用扫一扫功能。' }}
        </p>
        <div class="flex flex-col sm:flex-row gap-3">
          <button 
            @click="handleRetryPermission" 
            class="flex-1 py-3 bg-primary text-white font-medium rounded-lg hover:bg-primary/90 transition-colors"
          >
            重试
          </button>
          <button 
            @click="handleCancelPermission" 
            class="flex-1 py-3 bg-white text-gray-700 font-medium rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors"
          >
            取消
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'PermissionPreloader',
  data() {
    return {
      hasCameraPermission: false,
      permissionRequestInProgress: false,
      showPermissionPrompt: false,
      errorMessage: ''
    };
  },
  mounted() {
    // 页面加载后延迟一段时间再请求权限，避免影响页面加载性能
    setTimeout(() => {
      // 检测是否是移动设备
      const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
      if (isMobile) {
        this.showPermissionPrompt = true;
      } else {
        // 桌面设备仍然在后台静默请求
        this.preloadCameraPermission();
      }
    }, 1000);
  },
  methods: {
    async preloadCameraPermission() {
      // 如果已经请求过权限或正在请求中，则不再重复请求
      if (this.hasCameraPermission || this.permissionRequestInProgress) {
        return;
      }
      
      this.permissionRequestInProgress = true;
      this.errorMessage = '';
      
      try {
        // 尝试访问摄像头权限
        // 使用低分辨率来减少对设备资源的占用
        const stream = await navigator.mediaDevices.getUserMedia({
          video: {
            width: { ideal: 16 },
            height: { ideal: 16 },
            facingMode: 'environment' // 优先使用后置摄像头
          }
        });
        
        // 立即停止流，我们只需要权限
        stream.getTracks().forEach(track => track.stop());
        
        this.hasCameraPermission = true;
        this.showPermissionPrompt = false;
        console.log('摄像头权限已提前获取');
      } catch (error) {
        // 权限被拒绝或不可用，显示具体错误信息
        console.log('摄像头权限请求结果:', error.name);
        
        // 根据错误类型提供更具体的提示
        switch(error.name) {
          case 'NotAllowedError':
            this.errorMessage = '您拒绝了摄像头权限，请在设备设置中允许使用摄像头。';
            break;
          case 'NotFoundError':
            this.errorMessage = '未检测到可用的摄像头设备。';
            break;
          case 'NotReadableError':
            this.errorMessage = '摄像头被其他应用占用，请关闭其他使用摄像头的应用。';
            break;
          case 'OverconstrainedError':
            this.errorMessage = '无法满足摄像头的配置要求。';
            break;
          default:
            this.errorMessage = '无法访问摄像头，请确保已授予权限。';
        }
      } finally {
        this.permissionRequestInProgress = false;
      }
    },
    
    // 重试权限请求
    handleRetryPermission() {
      this.preloadCameraPermission();
    },
    
    // 取消权限请求
    handleCancelPermission() {
      this.showPermissionPrompt = false;
    },
    
    // 提供一个方法供其他组件检查权限状态
    checkCameraPermissionStatus() {
      return this.hasCameraPermission;
    }
  }
};
</script>

<style scoped>
/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.fade-in {
  animation: fadeIn 0.2s ease-out;
}
</style>